package org.zs.rocketclient.batch;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;

import java.util.ArrayList;
import java.util.List;

/**
 * @author madison
 * @description
 * @date 2021/7/4 11:02
 */
public class BatchProducer {
    public static void main(String[] args) throws MQClientException {
        // Instantiate a producer to send scheduled messages
        DefaultMQProducer producer = new DefaultMQProducer("BatchProducerGroupExample");
        producer.setNamesrvAddr("localhost:9876");
        // Launch producer
        producer.start();

        String topic = "BatchTopicTest";
        List<Message> messages = new ArrayList<>();
        messages.add(new Message(topic, "TagA", "OrderID001", "Hello world 0".getBytes()));
        messages.add(new Message(topic, "TagA", "OrderID002", "Hello world 1".getBytes()));
        messages.add(new Message(topic, "TagA", "OrderID003", "Hello world 2".getBytes()));
        try {
            producer.send(messages);
        } catch (Exception e) {
            e.printStackTrace();
            //handle the error
        }

        producer.shutdown();

        /**
         * Split into lists
         * The complexity only grow when you send large batch and you may not sure if it exceeds the size limit (1MiB).
         * {@link ListSplitter}
         * At this time, you’d better split the lists:
         */
        ListSplitter splitter = new ListSplitter(messages);
        while (splitter.hasNext()) {
            try {
                List<Message> listItem = splitter.next();
                producer.send(listItem);
            } catch (Exception e) {
                e.printStackTrace();
                //handle the error
            }
        }
    }
}
